//
//  HMComposeViewController.m
//  HMWeiBoOC
//
//  Created by GD on 16/9/17.
//  Copyright © 2016年 geduo. All rights reserved.
//

#import "HMComposeViewController.h"
#import "UILabel+HMLabel.h"
#import "HMUserAccountViewModel.h"
#import "HMUserAccount.h"
#import <SVProgressHUD.h>
#import "HMNetworkTools.h"


#import "HMWeiBoOC-Swift.h"

//@class HMComposeToolBarButtonType;
@interface HMComposeViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,HMComposeToolBarDelegate>

@property (nonatomic,strong) UILabel *titleLabel;

@property (nonatomic,strong) HMComposeTextView *textView; //无法导入具体的类?  -> 可以


@property (nonatomic,strong) HMComposeToolBar *toolBar;

@property (nonatomic,strong) HMComposePictureView *pictureView;
@end

@implementation HMComposeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupNav];
    [self setupUI];
}



-(void)setupUI{
     //  监听键盘的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
    [self.view addSubview:self.textView];
    [self.view addSubview:self.toolBar];
    [self.textView addSubview:self.pictureView];
    
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.equalTo(self.view);
        make.trailing.equalTo(self.view);
        make.bottom.equalTo(self.toolBar.mas_top);
    }];
    
    [_pictureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.textView);
        make.top.equalTo(self.textView).offset(100);
        make.width.equalTo(self.textView).offset(-20);
        make.height.equalTo(self.textView.mas_width).offset(-20);
    }];
    
//    __weak (typeof self)weakSelf = self;
        __weak HMComposeViewController *weakSelf = self;
    _pictureView.lastCellCallBack = ^{
        [weakSelf didSelectedPicture];
    };
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.leading.equalTo(self.textView);
        make.trailing.equalTo(self.textView);
        make.height.equalTo(@35);
    }];
    
    self.toolBar.name = nil ;
    self.toolBar.callBack1= nil;// 当闭包中有枚举的参数时,会导致闭包无法编译.!!!
    
    _toolBar.delegate1 = self;
    
//    self.toolBar.callBack = ^(HMComposeToolBarButtonType type){//OC无法回调swift 的闭包.
//        switch (type) {
//            case 0:
//                NSLog(@"图片");
//                break;
//                
//            default:
//                break;
//        }
//    }
    
//    _toolBar.callBack = ^(HMComposeToolBarButtonType:type){
//        switch (type){
//        case 0:
////            print("图片")
//        case 1:
////            print("@")
//        case 2:
////            print("#")
//        case 3:
////            print("表情")
//        case 4:
////            print("加号")
//            
//            
//        }
    
//    }
}

-(void)setupNav{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"🔙" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton *sendBtn = [[UIButton alloc] init];
    [sendBtn addTarget:self action:@selector(send) forControlEvents:UIControlEventTouchUpInside];
    
    [sendBtn setBackgroundImage:[UIImage imageNamed:@"common_button_orange"] forState:UIControlStateNormal];
    [sendBtn setBackgroundImage:[UIImage imageNamed:@"common_button_orange_highlighted"] forState:UIControlStateHighlighted];
    [sendBtn setBackgroundImage:[UIImage imageNamed:@"common_button_white_disable"] forState:UIControlStateDisabled];
    [sendBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateDisabled];
    sendBtn.backgroundColor = [UIColor orangeColor];
    
//    [sendBtn sizeToFit];
    sendBtn.frame = CGRectMake(0, 0, 45, 35);
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:sendBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    //中间的title
    self.navigationItem.titleView = self.titleLabel;
    
}

-(void)keyBoardFrameChange:(NSNotification *)noti{
    CGRect keyBoardFrame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    double duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [_toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(keyBoardFrame.origin.y - ScreenHeight);
    }];
    
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)send{
    NSLog(@"发送 点击");
    NSString *accessToken = [HMUserAccountViewModel sharedViewModel].userAccount.access_token;
    NSString *text = self.textView.text;
    
    [SVProgressHUD show];
    
    if (self.pictureView.images.count >0) {
        UIImage *firstImage = self.pictureView.images[0];
        [[HMNetworkTools sharedTools] updateWithAccess_token:accessToken status:text image:firstImage andCallBack:^(id response, NSError *error) {
            if (error != nil) {
                [SVProgressHUD showErrorWithStatus:@"网络请求异常!" ];
                return;
            }
            [SVProgressHUD showSuccessWithStatus:@"发送成功!"];
        }];
    }else{
    
    
        [[HMNetworkTools sharedTools] updateWithAccess_token:accessToken status:text andCallBack:^(id response, NSError *error) {
            
            if (error != nil) {
                [SVProgressHUD showErrorWithStatus:@"网络请求异常!" ];
                return;
            }
            [SVProgressHUD showSuccessWithStatus:@"发送成功!"];
        }];
    }
    
    [self cancel];
}

-(void)cancel{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithTextColor:[UIColor darkGrayColor] fontSize:[UIFont systemFontOfSize:16]];
        NSString *name = [HMUserAccountViewModel sharedViewModel].userAccount.name;
        if (name) {
            _titleLabel.text = [NSString stringWithFormat:@"发微博\n%@",name];
            //富文本
            NSRange range = [_titleLabel.text rangeOfString:name];
            
            NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:_titleLabel.text];
            [attriStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],NSForegroundColorAttributeName:[UIColor brownColor]} range:range];
            _titleLabel.attributedText = attriStr;
        }else{
            _titleLabel.text = @"发微博";
        }
        
        _titleLabel.numberOfLines = 0;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [_titleLabel sizeToFit ];
    }
    return _titleLabel;
}

#pragma mark -  getter
-(HMComposeTextView *)textView{
    if (!_textView) {
        _textView = [[HMComposeTextView alloc]  init];
        _textView.placeHolder = @"别哭泣,老王会笑~别哭泣,老王会笑~别哭泣,老王会笑~别哭泣,老王会笑~别哭泣,老王会笑~别哭泣,老王会笑~别哭泣,老王会笑~别哭泣,老王会笑~别哭泣,老王会笑~";//计算属性
        _textView.alwaysBounceVertical = YES;
        _textView.delegate = self;
    }
    return _textView;
}

-(HMComposeToolBar *)toolBar{
    if (!_toolBar) {
        _toolBar = [[HMComposeToolBar alloc] init];
//        _toolBar.backgroundColor = [UIColor orangeColor];
        _toolBar.frame = CGRectMake(0, 100, self.view.bounds.size.width, 35);
        _toolBar.delegate1 = self;
    }
    return _toolBar;
}

-(HMComposePictureView *)pictureView{
    if (!_pictureView) {
        _pictureView = [[HMComposePictureView alloc] init];
        _pictureView.backgroundColor = self.textView.backgroundColor;
    }
    return _pictureView;
}

#pragma mark -UITextViewDelegate
-(void)textViewDidChange:(UITextView *)textView{
    self.navigationItem.rightBarButtonItem.enabled = textView.hasText;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark -HMComposeToolBarDelegate
-(void)didSelectedToolBarBtnWithBtn:(UIButton *)btn{
//    NSLog(@"youmeiyou");
    [self didSelectedPicture];
}


#pragma mark - UIImagePickerControllerDelegate

-(void)didSelectedPicture{
    UIImagePickerController *imagePictureCtr = [[UIImagePickerController alloc] init];
    imagePictureCtr.delegate = self;
     //  是否执行传入的来源类型
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imagePictureCtr.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else{
        imagePictureCtr.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    //  判断是否支持前置设置头
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
        NSLog(@"支持前置摄像头");
    }
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"支持后置摄像头");
    }
    
    [self presentViewController:imagePictureCtr animated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSLog(@"%@",info);
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    UIImage *scaleImage = [image scaleImageWithScaleWidth:200];
    
    [self.pictureView addImageWithImage:scaleImage];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}


@end
